import React from 'react';
import { connect } from 'react-redux';
import { messages, queryCurrencyPrecision, deepFullCopy, getQueryUrlParam } from 'share/common'
import moment from 'moment'
import constants from 'share/constants'
import { Form, Tabs, Spin, Row, Col, Affix, Button, message, Popconfirm } from 'antd';
import 'styles/request/base-request-detail.scss';
import ApproveHistory from 'components/template/approve-history'
import GiftRequestDetailA from 'containers/request/gift-request-detail/gift-request-detail-a'
import GiftRequestDetailB from 'containers/request/gift-request-detail/gift-request-detail-b'
import GiftRequestDetailC from 'containers/request/gift-request-detail/gift-request-detail-c'
import ReceiverInformation from 'containers/request/gift-request-detail/receiver-information'
import GiftRequestA from 'containers/request/gift-request/gift-request-detail-a'
import GiftRequestB from 'containers/request/gift-request/gift-request-detail-b'
import GiftRequestC from 'containers/request/gift-request/gift-request-detail-c'
import GiftRequestD from 'containers/request/gift-request/gift-request-detail-d'
import GiftReceiverInformation from 'containers/request/gift-request/receiver-information'

import SlideFrame from "components/slide-frame";
import EditContent from 'containers/request/gift-request-detail/edit-content';
import GiftEditContent from 'containers/request/gift-request/edit-content';
import menuRoute from 'routes/menuRoute'
import customField from 'share/customField'

import baseService from 'share/base.service'
import requestService from 'containers/request/request.service'
import adminApproveListService from "../setting/process-monitoring-platform/admin-approve-list.service";

import GoBackBtn from 'containers/request/btns/go-back-btn'
import config from 'config'
import httpFetch from 'share/httpFetch'
import approveService from 'containers/approve/approve.service'

const { TabPane } = Tabs;

class GiftRequestDeatil extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          loading: false,
          info: {}, // 申请单详情
          isShowEdit: false, // 是否显示编辑的抽屉
          originalFormInfo: {},
          saveLoading: false,
          submitLoading: false,
          returnLoading: false,
          deleteLoading: false,
          closeLoading: false,
          urgeLoading: false,
          signLoading: false,
          loseLoading: false,
          confLoading: false,
          valid: false,
          jobId: '',
          jobInfo: {},
          key: 1,
          tabkey: 1,
          editLines: false,
        }
    }

    componentDidMount () {
      this.getFormInfo()
    }

    // 获取岗位信息
    getJobInfo = () => {
      const { jobId } = this.state;
      baseService.getJobInfo(jobId).then(res => {
        this.setState({
          jobInfo: res.data
        })
      })
    }

    // 获取表单信息
    getFormInfo () {
      const { params, company } = this.props;
      this.setState({loading: true});
      requestService.getCustomForm(params.formOID).then(res => {
        this.setState({
          originalFormInfo: deepFullCopy(res.data)
        })
        this.getInfo()
      })
    }

    // 获取申请单详情
    getInfo () {
      const {applicationOID} = this.props.params;
      requestService.getRequestDetail(applicationOID).then(res => {
        this.setState({
          loading: false,
          info: res.data,
          approvalHistory: res.data.approvalHistorys,
          jobId: res.data.jobId
        }, () => {
          this.getJobInfo();
        })
      })
    }

    // 编辑
    onHandleEdit = () => {
      if(this.state.editLines){
        message.warning('已有一行正在编辑')
        return;
      }
      this.setState({
        isShowEdit: true
      })
    }

    // 抽屉关闭之后的回调函数
    isCallBack = (isChange) => {
      this.setState({isShowEdit: false, key: this.state.key + 1});
      if (isChange) {
        this.getFormInfo()
      }
      this.onChangeEdit(false)
    }

    // 提交和保存共同的接口入参数据
    commonData () {
      const { info } = this.state
      let custFormValues = info.custFormValues
      let custFormValuesJson = {}
      let custData = undefined
      let kq = undefined
      custFormValues && custFormValues.map(item => {
        custFormValuesJson[item.fieldCode] = item
        if (item.fieldName === "领用方式") {
          custData = Number(item.value)
        }else if (item.fieldName === "卡券类型"){
          kq = item.value
        }
      })
      console.log("custFormValues", custData, info.formCode)
      let giftReceiverDTOs = ((custData && custData === 1) || (kq === "002")) && this.childR ? this.childR.state.dataR : info.formCode === 'SQ004' ? this.childR ? this.childR.state.dataR : [] : []
      let dataA = ((custData && custData === 1) || (kq === "002")) && this.childA ? this.childA.state.dataA : []
      let dataB = this.childB ? this.childB.state.dataB : []
      let dataC = this.childC ? this.childC.state.dataC : []
      let dataD = this.childD ? this.childD.state.dataD : []
      let giftLineDTOs = [
        ...dataA,
        ...dataB,
        ...dataC,
        ...dataD
      ]
      info.giftApplication = {
        applicationOID: info.applicationOID,
        baseCurrencyAmount: info.totalAmount,
        businessCode: info.businessCode,
        companyCurrencyRate: 1,
        currencyCode: info.currencyCode,
        costCenterItemCode: custFormValuesJson.costcenter ? custFormValuesJson.costcenter.valueCode : '',
        costCenterItemName: custFormValuesJson.costcenter ? custFormValuesJson.costcenter.showValue : '',
        costCenterItemOID: custFormValuesJson.costcenter ? custFormValuesJson.costcenter.value : '',
        externalParticipantNumber: 0,
        externalParticipants: [],
        participantNum: 0,
        totalBudget: info.totalAmount,
        totalSubsidiesBudget: 0,
        expenseConfirmer: '',
        recipientsNum: custFormValuesJson.number ? custFormValuesJson.number.showValue : '',
        employeeId: info.applicant.employeeID,
        isDeleted: false,
        custFormValues,
        giftReceiverDTOs,
        giftLineDTOs
      }
      return info
    }

    // 保存为草稿
    onHandleSave = () => {
      let info = this.commonData()
      this.setState({saveLoading: true}, () => {
        requestService.giftRequestDetailTableSave(info).then(res => {
          this.setState({saveLoading: false})
          message.success(messages('request.key779'/*保存成功*/))
        })
      })
    }

    // 提交申请单
    onHandleSubmit = () => {
      let editingKeyA = this.childA ? this.childA.child.state.editingKey : ''
      let editingKeyB = this.childB ? this.childB.child.state.editingKey : ''
      let editingKeyC = this.childC ? this.childC.child.state.editingKey : ''
      let editingKeyD = this.childD ? this.childD.child.state.editingKey : ''
      let editingKeyR = this.childR ? this.childR.child.state.editingKey : ''
      if (editingKeyA || editingKeyB || editingKeyC || editingKeyD) {
        message.info("存在未保存的礼品，请先保存后再提交")
        return
      }
      if (editingKeyR) {
        message.info("存在未保存的接收人信息，请先保存后再提交")
        return
      }
      let data = this.commonData()
      let { totalAmount, giftApplication, formCode } = data
      const { info } = this.state;
      if (['SQ002', 'SQ004'].includes(formCode)) {
        let { giftReceiverDTOs } = giftApplication
        let receiverTotalAmount = 0
        let totalAmountVaild = 0
        giftReceiverDTOs && giftReceiverDTOs.map(item => {
          receiverTotalAmount += item.amount
        })
        giftApplication.giftLineDTOs.map(i=> {
            totalAmountVaild += i.amount
        })
        let custFormValues = info.custFormValues
        let custFormValuesJson = {}
        console.log(totalAmountVaild,receiverTotalAmount,'金额')
        if (formCode === 'SQ002') {
          let type = '' // 领用方式
          let fafangleixing = ''
          custFormValues && custFormValues.map(item => {
            custFormValuesJson[item.fieldCode] = item.showValue
            if (item.fieldCode === 'custlist') {
              type = item.valueCode
            }else if (item.fieldCode === 'fafangleixing') {
              fafangleixing = item.value
            }
          })
          if (this.showGiftReceiverInformation() && Number(totalAmountVaild).toFixed(2) !== Number(receiverTotalAmount).toFixed(2) && type === '1') {
            message.info('接收人接收总金额应等于礼品申请总金额')
            return
          } else if (this.showGiftReceiverInformation() && fafangleixing === '001' && Number(totalAmountVaild).toFixed(2) !== Number(receiverTotalAmount).toFixed(2)) {
            message.info('接收人接收总金额应等于礼品申请总金额')
            return
          }
        } else {
          if (Number(totalAmountVaild).toFixed(2) !== Number(receiverTotalAmount).toFixed(2)) {
            message.info('接收人接收总金额应等于礼品申请总金额')
            return
          }
        }
      }
      this.setState({submitLoading: true}, () => {
        requestService.giftRequestDetailTableSubmit(info).then(res => {
          this.setState({submitLoading: false})
          message.success(messages('request.key197'/*提交成功*/))
          menuRoute.goBack(this)
        }).catch(() => {
          this.setState({submitLoading: false})
        })
      })
    }

    // 撤回
    onHandleReturn = () => {
      let { info } = this.state
      let data = {
        entities: [{
          entityOID: info.applicationOID,
          entityType: '1001'
        }]
      }
      this.setState({returnLoading: true}, () => {
        requestService.giftApplicationReturn(data).then(res => {
          this.setState({returnLoading: false})
          message.success(messages('request.key804'/*撤回成功*/))
          menuRoute.goBack(this)
        })
      })
    }

    // 删除
    onHandleDelete = () => {
      this.setState({deleteLoading: true})
      let { info } = this.state
      requestService.deleteRequest(info.applicationOID).then(res => {
        this.setState({ deleteLoading: false });
        message.success(messages('common.delete.success', { name: '' }));
        menuRoute.goBack(this)
      }).catch(e => {
        this.setState({ deleteLoading: false });
        errorMessage(e.response);
      })
    }

    // 关闭
    onHandleClose = () => {
      this.setState({closeLoading: true})
      let { info } = this.state
      let params = {
        applicationOID: info.applicationOID,
        participantOID: info.applicantOID
      }
      requestService.closeApplications(params).then(res => {
        this.setState({ closeLoading: false });
        message.success(messages('request.key548')/*关闭成功*/)
        menuRoute.goBack(this)

      }).catch(e => {
        this.setState({ closeLoading: false });
        errorMessage(e.response);
      })
    }

    // 催办
    handleUrge = () => {
      const {info} = this.state;
      if (info.approvalChains && info.approvalChains.length > 0) {
        const {approverOID, entityOID, entityType} = info.approvalChains[0];
        const { applicantOID, businessCode, formOID } = info
        this.setState({
          urgeLoading: true
        }, () => {
          let params ={
            approverOID,
            entityOID,
            entityType,
            applicantOID,
            businessCode,
            formOID
          }
          adminApproveListService.postPressMessage(params)
            .then(res=>{
              if(res.data){
                message.info(messages('components.key746')/*已向审批人发出催办消息*/);
                setTimeout(() => {
                  this.setState({ urgeLoading:false })
                }, 3000)
              }
            }).catch(e => {
            this.setState({ urgeLoading:false })
            message.error(`${e.response.data.message}`)
          });
        })
      }
    }

    onHandleSign =()=>{
      let infoData = this.commonData()
      this.setState({signLoading : true});
      let lineDTOS =  infoData.giftApplication.giftLineDTOs;
      let valid = false;
      if(lineDTOS.length==0){
        message.warning('缺少礼品行');
        this.setState({signLoading : false});
        return;
      }
      lineDTOS = lineDTOS.filter(i=> i.distributionStatus == '已发货' && i.signingStatus == '待签收')
      try {
        lineDTOS.forEach(i => {
          if(i.distributionStatus != '已发货'){
            valid =true;
            message.warning(`${i.formType==2 ? '礼品卡' : i.formType==3 ? 'BOG' : '现金券'}${i.type}未发货`);
            throw Error();
          }
          if(i.signingStatus != '待签收'){
            valid =true;
            message.warning(`${i.formType==2 ? '礼品卡' : i.formType==3 ? 'BOG' : '现金券'}${i.type}${i.signingStatus}`);
            throw Error();
          }
        })
      } catch(e){
      }
      if(valid){
        this.setState({signLoading : false});
        return;
      }
      let data = [];
      lineDTOS.forEach(i => {
        let item = {
          businessCode: i.lineNo.split('-')[0],
          lineCode: i.lineNo,
          state: 'hand_signed',
        }
        data.push(item);
      })
      httpFetch.post(`${config.baseUrl}/api/bath/send/ecs/active?roleType=TENANT`, data).then(res => {
        if(res.data.success){
          message.success('卡券激活成功');
          this.getInfo();
          this.onHandleConfirm();
          this.setState({signLoading : false});
        }else{
          message.error(`卡券激活失败，请稍后重试`)
          this.setState({signLoading : false});
        }
      }).catch((e) => {
        this.setState({signLoading: false})
        errorMessage(e.response);
      })
    }

    onHandleLose =()=>{
      let infoData = this.commonData()
      this.setState({loseLoading : true});
      let lineDTOS =  infoData.giftApplication.giftLineDTOs;
      let valid = false;
      if(lineDTOS.length==0){
        message.warning('缺少礼品行');
        this.setState({loseLoading : false});
        return;
      }
      lineDTOS = lineDTOS.filter(i=> i.distributionStatus == '已发货' && i.signingStatus == '待签收')
      try {
        lineDTOS.forEach(i => {
          if(i.distributionStatus != '已发货'){
            valid =true;
            message.warning(`${i.formType==2 ? '礼品卡' : i.formType==3 ? 'BOG' : '现金券'}${i.type}未发货`);
            throw Error();
          }
          if(i.signingStatus != '待签收'){
            valid =true;
            message.warning(`${i.formType==2 ? '礼品卡' : i.formType==3 ? 'BOG' : '现金券'}${i.type}${i.signingStatus}`);
            throw Error();
          }
        })
      } catch(e){
      }
      if(valid){
        this.setState({loseLoading : false});
        return;
      }
      let data = [];
      lineDTOS.forEach(i => {
        let item = {
          businessCode: i.lineNo.split('-')[0],
          lineCode: i.lineNo,
          state: 'hand_lost',
        }
        data.push(item);
      })
      httpFetch.post(`${config.baseUrl}/api/bath/send/ecs/invalid?roleType=TENANT`, data).then(res => {
        if(res.data.success){
          message.success('卡券作废成功');
          this.getInfo();
          this.onHandleConfirm();
          this.setState({loseLoading : false});
        }else{
          message.error(`卡券作废失败，请稍后重试`)
          this.setState({loseLoading : false});
        }
      }).catch((e) => {
        this.setState({loseLoading: false})
        errorMessage(e.response);
      })
    }

    onHandleConfirm =()=>{
      let infoData = this.state.info;
      let type = 'pass';
      let entities = [];
      let item = JSON.stringify({
        approverOID: infoData.approvalChain.approverOID,
        entityOID: infoData.approvalChain.entityOID,
        entityType: infoData.approvalChain.entityType,
      });
      entities.push(JSON.parse(item))
      let params = {
        entities,
      };
      this.setState({confLoading: true});
      approveService[type === 'pass' ? 'handleRequestApprovePass' : 'handleRequestApproveReject'](params).then(res => {
        if (res.status === 200) {
          this.setState({confLoading : false});
          message.success("确认成功");
          menuRoute.goBack(this)
        }
      }).catch(e => {
        this.setState({confLoading : false});
        message.error(`${messages('common.operate.filed'/*操作失败*/)}，${e.response.data.message}`)
      })
    }

    onChangeEdit = (value)=>{ //判断是否存在行编辑
      this.setState({editLines: value})
    }

    lineSumChange = () =>{
      let lengthB = this.childB && this.childB.state.data  ? this.childB.state.data.length : 0
      let lengthC = this.childC && this.childB.state.data  ? this.childC.state.data.length : 0
      let lengthD = this.childD && this.childB.state.data  ? this.childD.state.data.length : 0
      if((lengthB+lengthC+lengthD)>=30){
        message.info('行数量超过30行!')
        return true;
      }
      return false;
    }

    showGiftReceiverInformation() {
      const { loading, info: {custFormValues}, approvalHistory, isShowEdit, originalFormInfo, saveLoading, submitLoading, returnLoading, deleteLoading, closeLoading, urgeLoading, jobInfo, signLoading, loseLoading, confLoading, editLines } = this.state
      let type = '' // 领用方式
      let custFormValuesJson = {}
      custFormValues && custFormValues.map(item => {
        custFormValuesJson[item.fieldCode] = item.showValue
        if (item.fieldCode === 'custlist') {
          type = item.valueCode
        }
      })

      const typeKq =  custFormValuesJson.kq ? custFormValuesJson.kq: ''//卡券类型
      const fafangleixing =  custFormValuesJson.fafangleixing ? custFormValuesJson.fafangleixing: ''//发放类型

      return (
        (typeKq === "电子卡券" && fafangleixing === "直发")
        || (typeKq === "电子卡券" && fafangleixing === "派发" && type === '1')
        || (typeKq === "实体卡券" && type === '1')
      )
    }

    render() {
      const { loading, info, approvalHistory, isShowEdit, originalFormInfo, saveLoading, submitLoading, returnLoading, deleteLoading, closeLoading, urgeLoading, jobInfo, signLoading, loseLoading, confLoading, editLines } = this.state
      const {applicationOID, formOID, id} = this.props.params;
      const backUrlKey = getQueryUrlParam('backUrlKey')
      const nodeName=info.approvalChain&&info.approvalChain.brmsRemark
      const returnUrl = this.props.location.pathname.split('/')[2]
      const approve=this.props.location.pathname.indexOf('approve-request-detail') > -1;
      let {giftApplication, applicationParticipant} = info
      let receiveStatus = giftApplication && giftApplication.receiveStatus
      let closed = applicationParticipant && applicationParticipant.closed
      let applicant = info.applicant || {}; //申请人信息
      let totalAmount = this.filterMoney(info.totalAmount || 0, queryCurrencyPrecision(info.currencyCode), true);
      let custFormValues = info.custFormValues
      let copyCustFormValues = deepFullCopy(custFormValues)
      let isEdit = ['1001', '10011000', '10011001', '10011002'].includes(`${info.status}${info.rejectType}`)
      let custFormValuesJson = {}
      let type = '' // 领用方式
      custFormValues && custFormValues.map(item => {
        custFormValuesJson[item.fieldCode] = item.showValue
        if (item.fieldCode === 'custlist') {
          type = item.valueCode
        } else if (item.fieldCode === "company") {
          custFormValuesJson[item.fieldCode] = item.valueCode
        }
      })
      custFormValues && custFormValues.map((i,index ) => { //不显示逻辑判断字段
        if (i.fieldCode === 'luojipanduan') {
          custFormValues.splice(index, 1)
        }
      })
      const typeKq =  custFormValuesJson.kq ? custFormValuesJson.kq: ''//卡券类型
      const fafangleixing =  custFormValuesJson.fafangleixing ? custFormValuesJson.fafangleixing: ''//发放类型
      let valid = true; //签收遗失按钮禁用
      if(info.giftApplication){
         const lineDTOS =  info.giftApplication.giftLineDTOs;
          lineDTOS.forEach(i => {
            if(i.distributionStatus == '已发货' && i.signingStatus == '待签收'){
              valid=false
            }
          })
          lineDTOS.forEach(i => {
            if(i.distributionStatus != '已发货' || i.signingStatus == null){
              valid=true
            }
          })
      }
      let validConf = false; //整单确认按钮禁用
      if(info.giftApplication){
          const lineDTOS =  info.giftApplication.giftLineDTOs;
          lineDTOS.forEach(i => {
            if(!(i.distributionStatus == '已发货' && i.signingStatus != '待签收' && i.signingStatus != null)){
              validConf= true
            }
          })
      }
      let requestInfo = (
        <Spin spinning={loading}>
          <div className="top-info">
            <Row className="row-container">
              <span className="top-info-name">{applicant.fullName}</span>
              <span className="detail-info">
                {messages('request.key3'/*工号*/)}：{applicant.employeeID}
                <span className="ant-divider"/>
                {messages('request.key4'/*部门*/)}：{applicant.departmentName || '-'}
                <span className="ant-divider"/>
                {messages('common.user.company')/*员工公司*/}：{applicant.companyName || '-'}
              </span>
            </Row>
            <Row className="row-container">
              <span className="detail-info detail-info-first">{info.formName}：{info.businessCode}</span>
              <span className="detail-info">
                {messages('request.key5'/*提交日期*/)}：{moment(info.submittedDate).format('YYYY-MM-DD')}
                {info.submittedBy && applicant.userOID !== info.submittedBy &&
                `，${messages('request.key447',{arg1: info.submittedName}/*由 {arg1} 代提*/)}`}
              </span>
              <span className="detail-info">
                {messages('request.key6'/*当前状态*/)}：
                {constants.expenseStatus.map(item => {
                  if (item.value === `${info.status}${info.rejectType}` || item.value === `${info.status}`) return item.label
                })}
              </span>
            </Row>
            <Row className="row-container">
              <span className="amount">
                {messages('request.key9'/*总金额*/)}：{info.currencyCode} {totalAmount}
              </span>
            </Row>
          </div>
        </Spin>
      );
      let detailContent = (
        <Spin spinning={loading}>
          <div className="tab-container">
            <h3 className="sub-header-title">
              {messages('request.key760'/*申请单头信息*/)}
              {isEdit && ['SQ001', 'SQ002', 'SQ003', 'SQ004', 'SQ021', 'SQ019', 'SQ018'].includes(info.formCode) && (<span className="sub-header-title-edit" onClick={this.onHandleEdit}>{messages('request.key761'/*编辑*/)}</span>)}
            </h3>
            {custFormValues && customField.renderFields(custFormValues.filter(i=>{
              if((typeKq=== '001' || typeKq=== '实体卡券') && i.fieldCode == 'fafangleixing'){
                return;
              }
              return i;
            }), info, applicant, undefined, undefined)}
          </div>
        </Spin>
      );
      return (
        <div className="base-request-detail background-transparent">
          {/* 申请单信息 */}
          <div className="tabs-info" style={{position: 'relative'}}>
            <Tabs type="card" defaultActiveKey="1" onChange={(i)=>{
              this.setState({tabkey : i})
            }}>
              <TabPane tab={messages('request.key11'/*申请单信息*/)} key="1">
                {requestInfo}
              </TabPane>
              {
                approvalHistory && approvalHistory.length > 0 ? (<TabPane tab={messages('request.key12'/*审批历史*/)} key="2">
                <ApproveHistory approvalChains={info.approvalChains}
                                isShowReply={this.props.params.pageFrom === 'my' && info.status === 1003}
                                businessCode={info.businessCode}
                                approvalHistory={approvalHistory}
                                applicantInfo={applicant}
                                formCode={info.formCode}
                                needApplicantConfirm={info.needApplicantConfirm}/>
              </TabPane>) : ''
              }
            </Tabs>
          </div>
          {this.state.tabkey == 1 && (<div className="request-info-wrapper">
            {/* 申请单头信息 */}
            <div className="request-info">
              {detailContent}
            </div>
            {
              [ 'SQ021', 'SQ023'].includes(info.formCode) && (
                <div>
                  {/* 申请单行信息A  当领取方式的code为1  即礼品的时候  显示  其他则不显示 */}
                  {type === '1' && ['SQ002', 'SQ021'].includes(info.formCode) && (<GiftRequestDetailA onRef={ref => this.childA = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={id} totalAmount={totalAmount}></GiftRequestDetailA>)}
                  {/* 申请单行信息B */}
                  <GiftRequestDetailB onRef={ref => this.childB = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={id} totalAmount={totalAmount}></GiftRequestDetailB>
                  {/* 申请单行信息C */}
                  <GiftRequestDetailC onRef={ref => this.childC = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={id} totalAmount={totalAmount}></GiftRequestDetailC>
                  {/* 接收人信息 */}
                  {info.formCode === 'SQ002' || info.formCode === 'SQ021' ? (type === '1' && <ReceiverInformation onRef={ref => this.childR = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={id} totalAmount={totalAmount}></ReceiverInformation>) : <ReceiverInformation onRef={ref => this.childR = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={id}></ReceiverInformation>}
                </div>
              )
            }
            {
              ['SQ004'].includes(info.formCode) && (
                <div>
                  {/* 申请单行信息A  当领取方式的code为1  即礼品的时候  显示  其他则不显示 */}
                  {type === '1' && ['SQ002'].includes(info.formCode) && (<GiftRequestA onRef={ref => this.childA = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={id} totalAmount={totalAmount} onChangeEdit={this.onChangeEdit} editLines={editLines}></GiftRequestA>)}
                  {/* 申请单行信息B */}
                  <GiftRequestB onRef={ref => this.childB = ref} isCallBack={(isChange) => this.isCallBack(isChange)} nodeName={nodeName} info={info} formOID={formOID} applicationOID={applicationOID} id={id} totalAmount={totalAmount} approve={approve} onChangeEdit={this.onChangeEdit} editLines={editLines} lineSumChange={this.lineSumChange}></GiftRequestB>
                  {/* 申请单行信息C */}
                  {/* <GiftRequestC onRef={ref => this.childC = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={id} totalAmount={totalAmount} approve={approve} onChangeEdit={this.onChangeEdit} editLines={editLines} lineSumChange={this.lineSumChange}></GiftRequestC> */}
                  {/* 申请单行信息D */}
                  <GiftRequestD onRef={ref => this.childD = ref} isCallBack={(isChange) => this.isCallBack(isChange)} nodeName={nodeName} info={info} formOID={formOID} applicationOID={applicationOID} id={id} totalAmount={totalAmount} approve={approve} onChangeEdit={this.onChangeEdit} editLines={editLines} lineSumChange={this.lineSumChange}></GiftRequestD>
                  {/* 接收人信息 */}
                  {info.formCode === 'SQ002' ? ( ((typeKq === "电子卡券" && fafangleixing === "直发") || (typeKq === "电子卡券" && fafangleixing === "派发" && type === '1') || (typeKq === "实体卡券" && type === '1')) && <GiftReceiverInformation onRef={ref => this.childR = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={id} totalAmount={totalAmount} onChangeEdit={this.onChangeEdit} editLines={editLines}></GiftReceiverInformation>) : <GiftReceiverInformation onRef={ref => this.childR = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={id} onChangeEdit={this.onChangeEdit} editLines={editLines}></GiftReceiverInformation>}
                </div>
              )
            }
            {
              ['SQ002'].includes(info.formCode) && (
                <div>
                  {/* 申请单行信息A  当领取方式的code为1  即礼品的时候  显示  其他则不显示 */}
                  {type === '1' && ['SQ002'].includes(info.formCode) && (<GiftRequestA onRef={ref => this.childA = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={id} totalAmount={totalAmount} onChangeEdit={this.onChangeEdit} editLines={editLines}></GiftRequestA>)}
                  {/* 申请单行信息B */}
                  <GiftRequestB onRef={ref => this.childB = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={id} totalAmount={totalAmount} approve={approve} onChangeEdit={this.onChangeEdit} editLines={editLines} lineSumChange={this.lineSumChange}></GiftRequestB>
                  {/* 申请单行信息C */}

                  {
                    (typeKq !== '电子卡券' || (typeKq === '电子卡券' && custFormValuesJson.company === '104')) && <GiftRequestC onRef={ref => this.childC = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={id} totalAmount={totalAmount} approve={approve} onChangeEdit={this.onChangeEdit} editLines={editLines} lineSumChange={this.lineSumChange}></GiftRequestC>
                  }

                  {/* 申请单行信息D */}
                  <GiftRequestD onRef={ref => this.childD = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={id} totalAmount={totalAmount} approve={approve} onChangeEdit={this.onChangeEdit} editLines={editLines} lineSumChange={this.lineSumChange}></GiftRequestD>
                  {/* 接收人信息 */}
                  {
                    this.showGiftReceiverInformation() && <GiftReceiverInformation onRef={ref => this.childR = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={id} totalAmount={totalAmount} onChangeEdit={this.onChangeEdit} editLines={editLines}></GiftReceiverInformation>
                  }
                </div>
              )
            }
            {
              ['SQ003', 'SQ022'].includes(info.formCode) && (<GiftRequestDetailB onRef={ref => this.childB = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={id} onChangeEdit={this.onChangeEdit} editLines={editLines}></GiftRequestDetailB>)
            }
            {
              info.formCode === 'SQ003' &&  (
                <ReceiverInformation onRef={ref => this.childR = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={id}></ReceiverInformation>
              )
            }
          </div>)}
         <SlideFrame show={isShowEdit}
            title={messages('request.key760'/*申请单头信息*/)}
            key={this.state.key}
            content={info.formCode === 'SQ002'|| info.formCode === 'SQ004' ? GiftEditContent : EditContent}
            params={{custFormValues: copyCustFormValues, formOID, applicationOID, originalFormInfo, info, jobInfo, isShowEdit, id: id}}
            onClose={() => this.setState({ isShowEdit: false, key: this.state.key + 1 })}
            afterClose={(isChange) => this.isCallBack(isChange)}
            />
          <Affix offsetBottom={0} className='bottom-bar'>
            {
              isEdit && `${closed}` !== '1' && (<Button loading={submitLoading} onClick={this.onHandleSubmit} type="primary" style={{marginRight: '20px'}}>{messages("request.key765")/*提交申请单*/}</Button>)
            }
            {/* {
              保存为草稿
              isEdit && (<Button loading={saveLoading} onClick={this.onHandleSave} style={{margin: '0 20px'}}>{messages("request.key766")}</Button>)
            } */}
            {
              `${info.status}` === '1001' && ['SQ002', 'SQ003', 'SQ004'].includes(info.formCode) && (
                <Popconfirm title={messages('common.confirm.delete')} placement="topRight" onConfirm={this.onHandleDelete}>
                  <Button className="delete-btn" loading={deleteLoading} style={{marginRight: '20px'}}>{messages("request.key806")/*删除*/}</Button>
                </Popconfirm>
              )
            }
            {
              ['1002SQ021', '1002SQ022', '1002SQ023'].includes(`${info.status}${info.formCode}`) && (<Button loading={returnLoading} onClick={this.onHandleReturn} style={{marginRight: '20px'}} type="primary">{messages("request.key803")/*撤回*/}</Button>)
            }
            {
              ['1002SQ002', '1002SQ003', '1002SQ004'].includes(`${info.status}${info.formCode}`) && info.isBack && (<Button loading={returnLoading} onClick={this.onHandleReturn} style={{marginRight: '20px'}} type="primary">{messages("request.key803")/*撤回*/}</Button>)
            }
            {
              ['1012'].includes(`${info.status}`) && (<Button loading={returnLoading} onClick={this.onHandleReturn} style={{marginRight: '20px'}} type="primary">{messages("request.key808")/*快递丢失*/}</Button>)
            }
            {
              ['1002'].includes(`${info.status}`) ?
                <Button
                  disabled={urgeLoading}
                  onClick={() => this.handleUrge()}
                  style={{marginRight: '20px'}}
                  type="primary"
                >
                  催办
                </Button> : null
            }
            {
              `${receiveStatus}` === '1001' && `${closed}` !== '1' && ['SQ002', 'SQ003', 'SQ004'].includes(info.formCode) && (
                <Button loading={closeLoading} onClick={this.onHandleClose} style={{marginRight: '20px'}} type="primary">{messages("credit.key11")/*关闭*/}</Button>
              )
            }
            {
              `${closed}` !== '1' && ['SQ002'].includes(info.formCode) && typeKq === '实体卡券' && info.status != '1001' && (<Button disabled={signLoading || valid} onClick={this.onHandleSign} type="primary" style={{marginRight: '20px'}}>{"整单签收"}</Button>)
            }
            {
              `${closed}` !== '1' && ['SQ002'].includes(info.formCode) && typeKq === '实体卡券' && info.status != '1001' && (<Button disabled={loseLoading || valid} onClick={this.onHandleLose} type="primary" style={{marginRight: '20px'}}>{"整单遗失"}</Button>)
            }
            {
              `${closed}` !== '1' && ['SQ002'].includes(info.formCode) && typeKq === '实体卡券' && info.status != '1001' && (<Button disabled={confLoading || validConf || info.status == '1003'} onClick={this.onHandleConfirm} type="primary" style={{marginRight: '20px'}}>{"整单确认"}</Button>)
            }
            {
              `${closed}` !== '1' && ['SQ004'].includes(info.formCode) && info.status != '1001' && (<Button disabled={signLoading || valid} onClick={this.onHandleSign} type="primary" style={{marginRight: '20px'}}>{"整单签收"}</Button>)
            }
            {
              `${closed}` !== '1' && ['SQ004'].includes(info.formCode) && info.status != '1001' && (<Button disabled={loseLoading || valid} onClick={this.onHandleLose} type="primary" style={{marginRight: '20px'}}>{"整单遗失"}</Button>)
            }
            {
              `${closed}` !== '1' && ['SQ004'].includes(info.formCode) && info.status != '1001' && (<Button disabled={confLoading || validConf || info.status == '1003'} onClick={this.onHandleConfirm} type="primary" style={{marginRight: '20px'}}>{"整单确认"}</Button>)
            }
            <GoBackBtn backUrlKey={backUrlKey} />
          </Affix>
        </div>
      )
    }
}

GiftRequestDeatil.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    request: state.cache.request,
  }
}

const wrappedGiftRequestDeatil = Form.create()(GiftRequestDeatil);

export default connect(mapStateToProps)(wrappedGiftRequestDeatil)
